import * as Blockly from 'blockly/core';
import { JavascriptGenerator } from 'blockly/javascript';

function statementToCode(block: Blockly.Block, generator: JavascriptGenerator, name: string) {
    try {
        return generator.statementToCode(block, name).trim();
    } catch (error) {
        return undefined
    }
}

function valueToCode(block: Blockly.Block, generator: JavascriptGenerator, name: string) {
    try {
        return generator.valueToCode(block, name, 0).trim();
    } catch (error) {
        return undefined
    }
}

function getVariableName(block: Blockly.Block, name: string) {
    try {
        return block.workspace.getVariableById(block.getFieldValue(name))?.name
    } catch (error) {
        return undefined
    }
}

function getFieldValue(block: Blockly.Block, name: string) {
    try {
        return block.getFieldValue(name);
    } catch (error) {
        return undefined
    }
}

export function getValue(block: Blockly.Block, generator: JavascriptGenerator, name: string) {
    let val: string | undefined = undefined
    try {
        val = statementToCode(block, generator, name);
        if (val !== undefined) {
            return val
        }
        val = valueToCode(block, generator, name);
        if (val !== undefined) {
            return val
        }

        val = getVariableName(block, name);
        if (val !== undefined) {
            return val
        }
        val = getFieldValue(block, name);
        return val
    } catch (error) {
        val = undefined
    }
    return val
}

export function getLines(block: Blockly.Block, generator: JavascriptGenerator,name:string) {
    const body = block.getInputTargetBlock(name);
    let lines = ''
    if (body) {
        const line = generator.blockToCode(body)
        lines = (typeof line === 'string' ? line : line.join('\n'))
    }
    return lines
}